package com.cloudpark.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import net.sf.cglib.beans.BeanMap;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudpark.common.util.Constants;
import com.cloudpark.common.util.ObjectUtil;
import com.cloudpark.common.util.Pagination;
import com.cloudpark.model.entity.AdminUser;
import com.cloudpark.model.entity.AdminUserRole;
import com.cloudpark.model.entity.EstateWechat;
import com.cloudpark.model.entity.Park;
import com.cloudpark.model.entity.Role;
import com.cloudpark.model.entity.User;
import com.cloudpark.model.mapper.AdminUserMapper;
import com.cloudpark.model.mapper.AdminUserRoleMapper;
import com.cloudpark.model.mapper.RoleMapper;
import com.cloudpark.model.mapper.UserMapper;
import com.cloudpark.model.vo.AdminUserVo;
import com.cloudpark.model.vo.UserVo;
import com.cloudpark.service.EstateService;
import com.cloudpark.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private EstateService estateService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;
    @Autowired
    private AdminUserRoleMapper userRoleMapper;

    @Override
    public User findUserById(long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public AdminUser findByAccount(String account) {
        return adminUserMapper.selectByAccount(account);
    }

    @Override
    public List<AdminUserRole> findRolesByUserId(Long userId) {
        return userRoleMapper.selectByUserId(userId);
    }

	@Override
	public User findUserByOpenId(String openId) {
		List<User> list = userMapper.selectUserByOpenId(openId);
		if (ObjectUtil.isBlank(list)) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public void saveUser(User user) {
		if (ObjectUtil.isBigThanZero(user.getId())) {
			userMapper.updateByPrimaryKey(user);
		} else {
			userMapper.insert(user);
		}
	}

	@Override
	public Pagination queryUserList(Map<String, String> params, int start,
			int length, Long estateId) {
		Pagination pagination = new Pagination();
        String nickname = null == params.get("nickname") ? "" : params.get("nickname").toString();
        UserVo paramVo = new UserVo();
        if (ObjectUtil.isNotBlank(nickname)) {
        	paramVo.setNickname(nickname);
        }
        EstateWechat estateWechat = estateService.queryEstateWechatByEstateId(estateId);
        paramVo.setToken(estateWechat.getToken());
        int totalRows = userMapper.countBySelective(paramVo);
        paramVo.setCurrentPage(start / length + 1);
        paramVo.setNumPerPage(length);
        paramVo.setTotalRows(totalRows);
        paramVo.initPageParams();
        pagination.setTotalRows(totalRows);
        List<User> list = userMapper.selectBySelective(paramVo);
        List<UserVo> result = new ArrayList<UserVo>();
        if (ObjectUtil.isNotBlank(list)) {
        	for (User user : list) {
        		UserVo userVo = new UserVo();
        		userVo.setWechatName(estateWechat.getName());
        		BeanMap beanMap = BeanMap.create(userVo);
        		beanMap.putAll(BeanMap.create(user));
        		result.add(userVo);
        	}
        }
        pagination.setResultList(result);
        return pagination;
	}

	@Override
	public Pagination queryRoleList(Map<String, String> params, int start,
			int length, Long estateId) {
		Pagination pagination = new Pagination();
        String name = null == params.get("name") ? "" : params.get("name").toString();
        Role paramVo = new Role();
        if (ObjectUtil.isNotBlank(name)) {
        	paramVo.setName(name);
        }
        int totalRows = roleMapper.countBySelective(paramVo);
        paramVo.setCurrentPage(start / length + 1);
        paramVo.setNumPerPage(length);
        paramVo.setTotalRows(totalRows);
        paramVo.initPageParams();
        pagination.setTotalRows(totalRows);
        List<Role> list = roleMapper.selectBySelective(paramVo);
        pagination.setResultList(list);
        return pagination;
	}

	@Override
	public Pagination queryAdminUserList(Map<String, String> params, int start,
			int length, Long estateId) {
		Pagination pagination = new Pagination();
        String name = null == params.get("name") ? "" : params.get("name").toString();
        String account = null == params.get("account") ? "" : params.get("account").toString();
        AdminUser paramVo = new AdminUser();
        if (ObjectUtil.isNotBlank(name)) {
            paramVo.setName(name);
        }
        if (ObjectUtil.isNotBlank(account)) {
            paramVo.setAccount(account);;
        }
        paramVo.setEstateId(estateId);
        int totalRows = adminUserMapper.countBySelective(paramVo);
        paramVo.setCurrentPage(start / length + 1);
        paramVo.setNumPerPage(length);
        paramVo.setTotalRows(totalRows);
        paramVo.initPageParams();
        pagination.setTotalRows(totalRows);
        List<AdminUser> list = adminUserMapper.selectBySelective(paramVo);
        List<AdminUserVo> result = new ArrayList<AdminUserVo>();
        if (ObjectUtil.isNotBlank(list)) {
        	for (AdminUser adminUser : list) {
        		AdminUserVo adminUserVo = new AdminUserVo();
        		List<AdminUserRole> userRoles = userRoleMapper.selectByUserId(adminUser.getId());
        		if (ObjectUtil.isNotBlank(userRoles)) {
        			adminUserVo.setRoleId(userRoles.get(0).getRoleId());
        		}
        		BeanMap beanMap = BeanMap.create(adminUserVo);
        		beanMap.putAll(BeanMap.create(adminUser));
        		result.add(adminUserVo);
        	}
        }
        pagination.setResultList(result);
        return pagination;
	}

	@Override
	public List<AdminUser> findByAccountWithEstateId(String account,
			Long estateId) {
		AdminUser param = new AdminUser();
		param.setAccount(account);
		param.setEstateId(estateId);
		return adminUserMapper.selectByCondition(param);
	}

	@Override
	public void saveOrUpdateAdminUser(String adminUserId, String name,
			String account, String roleId, Long estateId) {
		AdminUser adminUser = null;
		if (ObjectUtil.isNotBlank(adminUserId)) {
			adminUser = adminUserMapper.selectByPrimaryKey(Long.valueOf(adminUserId));
			adminUser.setName(name);
			adminUser.setAccount(account);
			adminUser.setEstateId(estateId);
			adminUserMapper.updateByPrimaryKey(adminUser);
		} else {
			adminUser = new AdminUser();
			adminUser.setName(name);
			adminUser.setAccount(account);
			adminUser.setEstateId(estateId);
			adminUser.setCreatedTime(new Date());
			adminUser.setPassword(DigestUtils.sha256Hex(Constants.DEFAULT_PASSWORD));
			adminUserMapper.insert(adminUser);
		}
		// 处理权限
		userRoleMapper.deleteByUserId(adminUser.getId());
		AdminUserRole adminUserRole = new AdminUserRole();
		adminUserRole.setUserId(adminUser.getId());
		adminUserRole.setRoleId(Long.valueOf(roleId));
		userRoleMapper.insert(adminUserRole);
	}

	@Override
	public String queryRoleOptions(Long estateId) {
		List<Role> list = roleMapper.selectAll();
		if (ObjectUtil.isNotBlank(list)) {
			StringBuilder sb = new StringBuilder();
			for (Role role : list) {
				sb.append("<option value=\"").append(role.getId()).append("\">").append(role.getName()).append("</option>");
			}
			return sb.toString();
		}
		return null;
	}

	@Override
	public void saveAdminUser(AdminUser adminUser) {
		if (null != adminUser && adminUser.getId() > Constants.CONST_ZERO) {
			adminUserMapper.updateByPrimaryKey(adminUser);
		} else {
			adminUserMapper.insert(adminUser);
		}
	}
}
